package com.qf.filters;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class MyLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest reqq = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String uri = reqq.getRequestURI();
        if (uri.contains("login.jsp")){
            if (reqq.getSession().getAttribute("loginUser")!=null){
                response.sendRedirect("/index.jsp");
                return;
            }
        }else if (uri.contains("/cart") || uri.contains("/order")){
            if (reqq.getSession().getAttribute("loginUser") == null){
                response.sendRedirect("/login.jsp");
                return;
            }
        }else if (uri.contains("/cart")){
            if (reqq.getSession().getAttribute("loginUser") == null){
                response.sendRedirect("/login.jsp");
                return;
            }
        }
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
